package com.atguigu.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantRWTest {
    public static void main(String[] args) {
        MapUser mapUser = new MapUser();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{mapUser.write(finalI,finalI+"");},String.valueOf(finalI)).start();
        }
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{mapUser.readm(finalI);},String.valueOf(finalI)).start();
        }
    }
}
class MapUser{
    Map<Integer,String> map = new HashMap<>();
//    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//    public void write(Integer key,String value){
//        lock.writeLock().lock();
//        try {
//            System.out.println(Thread.currentThread().getName()+"正在写入");
//            map.put(key,value);
//            System.out.println(Thread.currentThread().getName()+"写入完成");
//        } finally {
//            lock.writeLock().unlock();
//        }
//    }
//    public void readm(Integer key){
//        lock.readLock().lock();
//        try {
//            System.out.println(Thread.currentThread().getName()+"正在读取");
//            String value = map.get(key);
//            System.out.println(Thread.currentThread().getName()+"读取完成:"+ value);
//        } finally {
//            lock.readLock().unlock();
//        }
//    }
    Lock lock = new ReentrantLock();
    public void write(Integer key,String value){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在写入");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入完成");
        } finally {
            lock.unlock();
        }
    }
    public void readm(Integer key){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在读取");
            String value = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取完成:"+ value);
        } finally {
            lock.unlock();
        }
    }
}
